package site.teamo.biu.flink.web.command;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import org.springframework.stereotype.Component;
import site.teamo.biu.flink.web.configuration.BiuFlinkConfig;

import javax.annotation.Resource;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author haocongshun
 * @date 2023/10/31 18:20:41
 */
@Component
public class CommandHandler {

    @Resource
    private BiuFlinkConfig biuFlinkConfig;

    public String execBiuFlinkTool(String toolHandlerClassName, String swapFile, List<String> extraLibFile) {
        List<String> libFiles = new LinkedList<>();
        libFiles.addAll(FileUtil.loopFiles(biuFlinkConfig.getSdkLibPath()).stream().map(File::getAbsolutePath).collect(Collectors.toList()));
        libFiles.addAll(FileUtil.loopFiles(biuFlinkConfig.getToolLibPath()).stream().map(File::getAbsolutePath).collect(Collectors.toList()));
        libFiles.addAll(extraLibFile);
        JavaProcess javaProcess = new JavaProcess(
                libFiles.toArray(new String[0]),
                "site.teamo.biu.flink.tool.BiuFlinkToolApplication",
                new String[]{toolHandlerClassName, swapFile});
        System.out.println("*******biu-flink-tool-" + toolHandlerClassName + "-" + swapFile + "*******\n" +
                javaProcess.exec()
                + "\n*******=end=*******");
        String result = FileUtil.readUtf8String(swapFile);
        FileUtil.del(swapFile);
        return result;
    }

    public Map<String, String> verifyFunctionPackage(Map<String, String> functionClassMap, String functionPackagePath) {
        File file = FileUtil.writeUtf8String(JSON.toJSONString(functionClassMap), biuFlinkConfig.getTempPath() + File.separator + "verify-function-package-" + System.currentTimeMillis() + ".json");
        String exec = execBiuFlinkTool("site.teamo.biu.flink.tool.handler.VerifyFunctionPackageHandler", file.getAbsolutePath(), ListUtil.of(functionPackagePath));
        return JSON.parseObject(exec, new TypeReference<Map<String, String>>() {
        });
    }
}
